<template>
  <!-- 导航组件begin -->
  <div class="nav-container" :class="{ sticky: isSticky }">
    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" :ellipsis="false"
        @select="handleSelect">
        <el-menu-item index="0">
            <img style="width: 100px" src="@/assets/images/element-plus-logo.svg" alt="Element logo" />
        </el-menu-item>
        <el-menu-item index="1">正阳餐厅</el-menu-item>
        <el-menu-item index="2" @click="router.push('/')">首页</el-menu-item>
        <el-menu-item index="3" @click="router.push('/orders')">我的订单</el-menu-item>
        <el-menu-item index="4" @click="router.push('/cart')">我的购物车</el-menu-item>
        <el-menu-item index="5" @click="router.push('/user')">我的</el-menu-item>
        
        <!-- 搜索框 -->
        <div class="search-container">
          <el-input
            v-model="searchQuery"
            placeholder="搜索美食..."
            :prefix-icon="Search"
            @keyup.enter="performSearch"
            clearable
            size="small"
            style="width: 250px;"
          >
            <template #append>
              <el-button :icon="Search" @click="performSearch" />
            </template>
          </el-input>
        </div>
        
        <!-- 登录状态显示 -->
        <el-menu-item v-if="!isLoggedIn" index="6" @click="dialogVisible = true">登录</el-menu-item>
        <el-menu-item v-if="!isLoggedIn" index="7" @click="registerDialogVisible = true">注册</el-menu-item>
        
        <!-- 登录后显示用户信息 -->
        <el-sub-menu v-if="isLoggedIn" index="8">
            <template #title>
                <el-avatar :size="32" :src="userInfo.avatar" style="margin-right: 8px;" />
                {{ userInfo.nickname || userInfo.email }}
            </template>
            <el-menu-item @click="router.push('/user')">个人中心</el-menu-item>
            <el-menu-item @click="router.push('/orders')">我的订单</el-menu-item>
            <el-menu-item @click="logout">安全退出</el-menu-item>
        </el-sub-menu>
    </el-menu>
  </div>
  <!-- 导航组件end -->

  <!-- 登录对话框begin -->
  <el-dialog
      v-model="dialogVisible"
      title="用户登录"
      width="500"
      :before-close="handleClose"
  >
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" label-width="80px">
          <el-form-item label="邮箱" prop="email">
              <el-input 
                  v-model="loginForm.email" 
                  placeholder="请输入邮箱地址" 
                  clearable
              />
          </el-form-item>
          <el-form-item label="密码" prop="password">
              <el-input 
                  v-model="loginForm.password" 
                  type="password" 
                  placeholder="请输入密码" 
                  show-password
                  clearable
              />
          </el-form-item>
          <el-form-item>
              <div style="display: flex; justify-content: space-between; width: 100%;">
                  <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
                  <el-button type="text" @click="showForgetPassword = true">忘记密码？</el-button>
              </div>
          </el-form-item>
      </el-form>
      
      <template #footer>
          <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleLogin" :loading="loading">
                  登录
              </el-button>
          </div>
      </template>
  </el-dialog>
  <!-- 登录对话框end -->

  <!-- 注册对话框 -->
  <el-dialog
      v-model="registerDialogVisible"
      title="用户注册"
      width="500"
  >
      <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" label-width="80px">
          <el-form-item label="昵称" prop="nickname">
              <el-input 
                  v-model="registerForm.nickname" 
                  placeholder="请输入昵称" 
                  clearable
              />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
              <el-input 
                  v-model="registerForm.email" 
                  placeholder="请输入邮箱地址" 
                  clearable
                  @blur="checkEmailForVerification"
              />
          </el-form-item>
          <el-form-item label="验证码" prop="verificationCode">
            <div style="display: flex; gap: 10px;">
              <el-input 
                  v-model="registerForm.verificationCode" 
                  placeholder="请输入验证码" 
                  clearable
                  style="flex: 1;"
              />
              <el-button 
                  type="primary" 
                  @click="sendVerificationCode" 
                  :disabled="!canSendCode || countdown > 0"
                  :loading="sendingCode"
              >
                  {{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="密码" prop="password">
              <el-input 
                  v-model="registerForm.password" 
                  type="password" 
                  placeholder="请输入密码（至少6位）" 
                  show-password
                  clearable
              />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                  v-model="registerForm.confirmPassword" 
                  type="password" 
                  placeholder="请再次输入密码" 
                  show-password
                  clearable
              />
          </el-form-item>
      </el-form>
      
      <template #footer>
          <div class="dialog-footer">
              <el-button @click="registerDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleRegister" :loading="registerLoading">
                  注册
              </el-button>
          </div>
      </template>
  </el-dialog>

  <!-- 忘记密码对话框 -->
  <el-dialog
      v-model="showForgetPassword"
      title="找回密码"
      width="400"
  >
      <el-form :model="forgetForm" label-width="80px">
          <el-form-item label="邮箱">
              <el-input 
                  v-model="forgetForm.email" 
                  placeholder="请输入注册邮箱" 
                  clearable
              />
          </el-form-item>
      </el-form>
      
      <template #footer>
          <div class="dialog-footer">
              <el-button @click="showForgetPassword = false">取消</el-button>
              <el-button type="primary" @click="handleForgetPassword">
                  发送重置邮件
              </el-button>
          </div>
      </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'

const router = useRouter()

// 用户信息接口
interface UserInfo {
    id: number
    email: string
    nickname: string
    avatar: string
    token: string
}

// 搜索相关状态
const searchQuery = ref('')
const isSticky = ref(false)

// 登录相关状态
const dialogVisible = ref(false)
const registerDialogVisible = ref(false)
const showForgetPassword = ref(false)
const loading = ref(false)
const registerLoading = ref(false)
const isLoggedIn = ref(false)
const userInfo = ref<UserInfo>({
    id: 0,
    email: '',
    nickname: '',
    avatar: '',
    token: ''
})

// 验证码相关状态
const countdown = ref(0)
const canSendCode = ref(false)
const sendingCode = ref(false)
const verificationCodeSent = ref(false)

// 表单引用
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()

// 登录表单
const loginForm = reactive({
    email: '',
    password: '',
    remember: false
})

// 注册表单
const registerForm = reactive({
    nickname: '',
    email: '',
    verificationCode: '',
    password: '',
    confirmPassword: ''
})

// 忘记密码表单
const forgetForm = reactive({
    email: ''
})

// 验证规则
const loginRules: FormRules = {
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
    ]
}

const registerRules: FormRules = {
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '昵称长度在2到20个字符之间', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    verificationCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { len: 6, message: '验证码长度为6位', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (rule: any, value: string, callback: any) => {
                if (value !== registerForm.password) {
                    callback(new Error('两次输入密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}

const activeIndex = ref('1')

const handleSelect = (key: string, keyPath: string[]) => {
    console.log(key, keyPath)
}

// 监听滚动实现吸顶效果
const handleScroll = () => {
  isSticky.value = window.scrollY > 50
}

// 执行搜索
const performSearch = () => {
  if (searchQuery.value.trim()) {
    router.push({
      path: '/search',
      query: { q: searchQuery.value }
    })
    searchQuery.value = ''
  }
}

// 检查邮箱格式以启用发送验证码按钮
const checkEmailForVerification = () => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  canSendCode.value = emailRegex.test(registerForm.email)
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!registerForm.email) {
    ElMessage.warning('请输入邮箱地址')
    return
  }

  sendingCode.value = true
  
  try {
    // 模拟发送验证码API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟验证码发送成功
    ElMessage.success(`验证码已发送至：${registerForm.email}`)
    verificationCodeSent.value = true
    
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    
  } catch (error) {
    ElMessage.error('发送验证码失败，请重试')
  } finally {
    sendingCode.value = false
  }
}

// 检查登录状态
const checkLoginStatus = () => {
    const token = localStorage.getItem('token')
    const userData = localStorage.getItem('userInfo')
    
    if (token && userData) {
        try {
            userInfo.value = JSON.parse(userData)
            isLoggedIn.value = true
        } catch (error) {
            console.error('解析用户信息失败', error)
            logout()
        }
    }
}

// 处理登录
const handleLogin = async () => {
    if (!loginFormRef.value) return
    
    try {
        await loginFormRef.value.validate()
        loading.value = true

        // 模拟登录API调用
        setTimeout(() => {
            // 模拟登录成功
            const mockUser: UserInfo = {
                id: 1,
                email: loginForm.email,
                nickname: loginForm.email.split('@')[0],
                avatar: 'https://via.placeholder.com/100x100?text=User',
                token: 'mock_jwt_token_' + Date.now()
            }

            // 保存用户信息
            userInfo.value = mockUser
            isLoggedIn.value = true

            // 保存到localStorage
            localStorage.setItem('token', mockUser.token)
            localStorage.setItem('userInfo', JSON.stringify(mockUser))
            
            if (loginForm.remember) {
                localStorage.setItem('rememberEmail', loginForm.email)
            }

            ElMessage.success('登录成功！')
            dialogVisible.value = false
            loading.value = false

            // 重置表单
            loginFormRef.value?.resetFields()
        }, 1000)

    } catch (error) {
        console.error('登录失败', error)
        loading.value = false
        ElMessage.error('登录失败，请检查输入')
    }
}

// 处理注册
const handleRegister = async () => {
    if (!registerFormRef.value) return
    
    try {
        await registerFormRef.value.validate()
        
        // 检查验证码是否正确（模拟验证）
        if (registerForm.verificationCode !== '123456') {
          ElMessage.error('验证码错误，请重新输入')
          return
        }

        registerLoading.value = true

        // 模拟注册API调用
        setTimeout(() => {
            // 模拟注册成功
            const mockUser: UserInfo = {
                id: Date.now(),
                email: registerForm.email,
                nickname: registerForm.nickname,
                avatar: 'https://via.placeholder.com/100x100?text=New',
                token: 'mock_jwt_token_' + Date.now()
            }

            // 自动登录
            userInfo.value = mockUser
            isLoggedIn.value = true
            localStorage.setItem('token', mockUser.token)
            localStorage.setItem('userInfo', JSON.stringify(mockUser))

            ElMessage.success('注册成功！已自动登录')
            registerDialogVisible.value = false
            registerLoading.value = false

            // 重置表单和验证码状态
            registerFormRef.value?.resetFields()
            countdown.value = 0
            verificationCodeSent.value = false
        }, 1000)

    } catch (error) {
        console.error('注册失败', error)
        registerLoading.value = false
    }
}

// 处理忘记密码
const handleForgetPassword = () => {
    if (!forgetForm.email) {
        ElMessage.warning('请输入邮箱地址')
        return
    }

    // 模拟发送重置邮件
    ElMessage.success(`重置密码邮件已发送至：${forgetForm.email}`)
    showForgetPassword.value = false
    forgetForm.email = ''
}

// 退出登录
const logout = () => {
    ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        // 清除登录状态
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        isLoggedIn.value = false
        userInfo.value = {
            id: 0,
            email: '',
            nickname: '',
            avatar: '',
            token: ''
        }
        ElMessage.success('已安全退出')
    }).catch(() => {
        // 用户取消
    })
}

// 对话框关闭前的处理
const handleClose = (done: () => void) => {
    if (loading.value) {
        ElMessage.warning('正在登录中，请稍候...')
        return
    }
    done()
}

// 初始化
onMounted(() => {
    checkLoginStatus()
    
    // 如果有记住的邮箱，自动填充
    const rememberedEmail = localStorage.getItem('rememberEmail')
    if (rememberedEmail) {
        loginForm.email = rememberedEmail
        loginForm.remember = true
    }
    
    // 添加滚动监听
    window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
.nav-container {
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  z-index: 1000;
  position: relative;
}

.nav-container.sticky {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  animation: slideDown 0.3s ease;
}

@keyframes slideDown {
  from {
    transform: translateY(-100%);
  }
  to {
    transform: translateY(0);
  }
}

.el-menu--horizontal>.el-menu-item:nth-child(1) {
    margin-right: auto;
}

:deep(.el-dialog__body) {
    padding: 20px;
}

:deep(.el-form-item) {
    margin-bottom: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  margin: 0 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-container {
    display: none;
  }
  
  .search-container.mobile-visible {
    display: flex;
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    padding: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    z-index: 1001;
  }
}
</style>